import asyncio
import time
from typing import Optional, Dict
import logging

from src.supabase_db.supabase import DBConnection

logger = logging.getLogger(__name__)

class MessageCacheItem:
    def __init__(self, user_id, thread_id: str, agent_code: str, msg_id: str, role: Optional[str] = 'assistant', event_type: Optional[str] = None):
        self.user_id = user_id,
        self.thread_id = thread_id
        self.agent_code = agent_code
        self.msg_id = msg_id
        self.content = ""
        self.role = role
        self.event_type = event_type
        self.finish_reason: Optional[str] = None
        self.last_update = time.time()  # 用于超时清理

    def append_content(self, chunk_content: str):
        self.content += chunk_content or ""
        self.last_update = time.time()

    def mark_finished(self, finish_reason: str):
        self.finish_reason = finish_reason
        self.last_update = time.time()

    def to_dict(self):
        d = {
            "project_id": self.thread_id,
            "agent_code": self.agent_code,
            "id": self.msg_id,
            "role": self.role,
            "content": self.content,
            "user_id": self.user_id
        }
        if self.finish_reason:
            d["finish_reason"] = self.finish_reason
        if self.event_type:
            d["event_type"] = self.event_type
        asyncio.create_task(save_chat_message(d))


async def cleanup_message_cache(cache: Dict[str, MessageCacheItem], timeout_seconds: int = 60):
    """
    清理超时未完成消息（没有 finish_reason，且超时）
    """
    while True:
        now = time.time()
        to_delete = []
        for msg_id, item in cache.items():
            if item.finish_reason is None and (now - item.last_update) > timeout_seconds:
                to_delete.append(msg_id)
        for msg_id in to_delete:
            print(f"Cleaning up timed-out message {msg_id}")
            cache.pop(msg_id)
        await asyncio.sleep(timeout_seconds // 2)

async def save_chat_message(chat_message: dict):
    try:
        db_conn = DBConnection()
        client = await db_conn.client
        update_result = await client.table('projects').insert(chat_message).execute()

    except Exception as e:
        logger.error(f"Error in background naming task for project {chat_message['project_id']}: {str(e)}")
    finally:
        # No need to disconnect DBConnection singleton instance here
        logger.info(f"Finished background naming task for project: {chat_message['project_id']}")
